package com.android.systemui.ios.views;

import android.app.UiModeManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.BatteryManager;
import android.os.Looper;
import android.provider.Settings;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import java.util.Locale;

import android.os.Message;
import android.os.Handler;
import android.widget.TextView;
import android.os.Vibrator;
import android.content.pm.PackageManager;

import com.android.systemui.ios.Constants;
import com.android.systemui.ios.IActionEventCallback;
import com.android.systemui.ios.IGuardService;
import com.android.systemui.ios.IStatusBarCallback;
import com.android.systemui.ios.R;

public class ShortcutIconView extends LinearLayout implements View.OnClickListener, IStatusBarCallback {

    private final String KEY_NO_DISTURB = "no_disturb_icon_show";
    static final String TAG = "IpShortcutMainLayout";

    private IGuardService mService;
    private IActionEventCallback mCallback;
    private ShortcutSlideView mSlideControlBrightness;
    private ShortcutSlideView mSlideControlVolume;

    private ImageView mIconWifi;
    private ImageView mIconBt;
    private ImageView mIconDrop;
    private ImageView mIconAirplane;
    private ImageView mIconScreenLock;
    private TextView mIconNoDisturb;

    private TextView mBarBatPercent;
    private ImageView mBarSignalSim1;
    private ImageView mBarSignalSim2;
    private TextView mBarCarrierSim1;
    private TextView mBarCarrierSim2;
    private ImageView mBarTypeSim1;
    private ImageView mBarTypeSim2;
    private ImageView mBarWifi;
    private ImageView mBarHeadset;
    private ImageView mBarBluetooth;
    private View mBarLine2Layout;

    private ImageView mIconTorch;
    private ImageView mIconClock;
    private ImageView mIconCalc;
    private ImageView mIconCamera;

    private ImageView mIconQrcode;
    private ImageView mIconRecorder;
    private ImageView mIconNight;
    private ImageView mIconSilent;
    private int mVolumeMax;
    private int mVolumeProgress;

    private boolean mAutomatic;

    private boolean mIsAirplaneMode;
    private boolean mWifiVisible;
    private boolean mHotspotEnableInTouch;
    private int mWifiLevel;
    private int mEarphonePlugState = 0;
    private Vibrator mVibrator;

    public ShortcutIconView(Context context) {
        this(context, null, 0);
    }

    public ShortcutIconView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ShortcutIconView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mVibrator = (Vibrator) getContext().getSystemService(Context.VIBRATOR_SERVICE);

        int automatic = Settings.System.getInt(context.getContentResolver(),
                Settings.System.SCREEN_BRIGHTNESS_MODE,
                Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
        mAutomatic = automatic != Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL;
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        mSlideControlBrightness = (ShortcutSlideView) findViewById(R.id.ip_shortcut_slide_control_brightness);
        mSlideControlVolume = (ShortcutSlideView) findViewById(R.id.ip_shortcut_slide_control_volume);

        mIconWifi = (ImageView) findViewById(R.id.ip_shortcut_icon_wifi);
        mIconBt = (ImageView) findViewById(R.id.ip_shortcut_icon_bt);
        mIconDrop = (ImageView) findViewById(R.id.ip_shortcut_icon_airdrop);
        mIconAirplane = (ImageView) findViewById(R.id.ip_shortcut_icon_airplane);
        mIconScreenLock = (ImageView) findViewById(R.id.ip_shortcut_icon_lock);
        mIconNoDisturb = (TextView) findViewById(R.id.ip_shortcut_icon_nodisturb);

        mIconTorch = (ImageView) findViewById(R.id.ip_shortcut_icon_torch);
        mIconClock = (ImageView) findViewById(R.id.ip_shortcut_icon_clock);
        mIconCalc = (ImageView) findViewById(R.id.ip_shortcut_icon_calc);
        mIconCamera = (ImageView) findViewById(R.id.ip_shortcut_icon_camera);

        mIconQrcode = (ImageView) findViewById(R.id.ip_shortcut_icon_qrcode);
        mIconRecorder = (ImageView) findViewById(R.id.ip_shortcut_icon_recorder);
        mIconNight = (ImageView) findViewById(R.id.ip_shortcut_icon_night);

        mIconSilent = (ImageView) findViewById(R.id.ip_shortcut_icon_silent);

        mBarBatPercent = findViewById(R.id.ip_shortcut_bar_bat_percent);
        mBarSignalSim1 = findViewById(R.id.ip_shortcut_bar_sim1_signal);
        mBarSignalSim2 = findViewById(R.id.ip_shortcut_bar_sim2_signal);
        mBarCarrierSim1 = findViewById(R.id.ip_shortcut_bar_sim1_carrier);
        mBarCarrierSim2 = findViewById(R.id.ip_shortcut_bar_sim2_carrier);
        mBarTypeSim1 = findViewById(R.id.ip_shortcut_bar_sim1_net_type);
        mBarTypeSim2 = findViewById(R.id.ip_shortcut_bar_sim2_net_type);
        mBarWifi = findViewById(R.id.ip_shortcut_bar_wifi);
        mBarHeadset = findViewById(R.id.ip_shortcut_bar_headset);
        mBarBluetooth = findViewById(R.id.ip_shortcut_bar_bluetooth);
        mBarLine2Layout = findViewById(R.id.ip_shortcut_bar_line2_layout);

        mIconWifi.setOnClickListener(this);
        mIconBt.setOnClickListener(this);
        mIconDrop.setOnClickListener(this);
        mIconAirplane.setOnClickListener(this);
        mIconScreenLock.setOnClickListener(this);
        mIconNoDisturb.setOnClickListener(this);
        mIconTorch.setOnClickListener(this);
        mIconClock.setOnClickListener(this);
        mIconCalc.setOnClickListener(this);
        mIconCamera.setOnClickListener(this);
        mIconQrcode.setOnClickListener(this);
        mIconRecorder.setOnClickListener(this);
        mIconNight.setOnClickListener(this);
        mIconSilent.setOnClickListener(this);

//        mSlideControlBrightness.setMaxMin(mMaximumBacklight, mMinimumBacklight, true);
        mSlideControlBrightness.setProgress(getCurrentBrightness());
        mSlideControlBrightness.setOnShortcutSlideChangedListener(new ShortcutSlideView.OnShortcutSlideChangedListener() {

            @Override
            public void onChanged(int max, int min, int progress, boolean tracking) {
                updateBrightness(max, min, progress, tracking);
            }
        });

        mSlideControlVolume.setOnShortcutSlideChangedListener(new ShortcutSlideView.OnShortcutSlideChangedListener() {

            @Override
            public void onChanged(int max, int min, int progress, boolean tracking) {
                if (mService != null) {
                    mService.setStreamVolume(AudioManager.STREAM_MUSIC, progress);
                }
            }
        });

        setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mCallback != null) {
                    mCallback.onShortcutClose();
                }
            }
        });
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_BATTERY_CHANGED);
        filter.addAction(Intent.ACTION_HEADSET_PLUG);
        filter.addAction("android.ext.UI_MODE_CHANGED");
        filter.addAction("android.ext.action_button_done");
        getContext().registerReceiver(mReceiver, filter);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        getContext().unregisterReceiver(mReceiver);
    }

    public void setActionEventCallback(IGuardService service, IActionEventCallback callback) {
        mService = service;
        mCallback = callback;

        if (service != null) {
            if (mSlideControlBrightness != null) {
                mSlideControlBrightness.setMaxMin(service.getBrightnessMax(), service.getBrightnessMin(), true);
            }
            mVolumeMax = service.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
            mVolumeProgress = service.getStreamVolume(AudioManager.STREAM_MUSIC);
            mSlideControlVolume.setMaxMin(mVolumeMax, 0, true);
            mSlideControlVolume.setProgress(mVolumeProgress);
        }
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
           /* if (RecordService.ACTION_SCREEN_RECORDER.equals(action)) {
                boolean recording = intent.getBooleanExtra("is_recording", RecordService.isInRecording);
                mRecorderCountDown = recording ? 0 : 100;
                mIconRecorder.setImageResource(recording ?
                        R.drawable.iphone_control_panel_screenrecord_on :
                        R.drawable.iphone_control_panel_screenrecord_off);
            } else */
            if ("android.ext.UI_MODE_CHANGED".equals(action)) {
                updateDarkMode();
            } else if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
                int level = (int) (100f
                        * intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0)
                        / intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100));
                mBarBatPercent.setText(String.format(Locale.US, "%d%%", level));
            } else if (Intent.ACTION_HEADSET_PLUG.equals(action)) {
                mEarphonePlugState = intent.getIntExtra("state", 0);
                mHandler.removeMessages(MSG_HEADSET);
                mHandler.sendEmptyMessageDelayed(MSG_HEADSET, 200);
            } else if ("android.ext.action_button_done".equals(action)) {
                handleActionButton();
            }
        }
    };

    private int mRecorderCountDown = 100;
    private final Runnable mRecorderCountDownRunnable = new Runnable() {

        @Override
        public void run() {
            switch (mRecorderCountDown) {
                case 0:
                    if (mService != null) {
                        mIconRecorder.setImageResource(R.drawable.iphone_control_panel_screenrecord_on);
                        mService.setScreenRecording(true);
                    }
                    break;
                case 1:
                    mIconRecorder.setImageResource(R.drawable.iphone_control_panel_screenrecord_1);
                    mRecorderCountDown--;
                    postDelayed(this, 1000);
                    break;
                case 2:
                    mIconRecorder.setImageResource(R.drawable.iphone_control_panel_screenrecord_2);
                    mRecorderCountDown--;
                    postDelayed(this, 1000);
                    break;
                case 3:
                    mIconRecorder.setImageResource(R.drawable.iphone_control_panel_screenrecord_3);
                    mRecorderCountDown--;
                    postDelayed(this, 1000);
                    break;
                default:
                    mIconRecorder.setImageResource(R.drawable.iphone_control_panel_screenrecord_off);
                    break;
            }
        }
    };

    private final Runnable mDarkModeNightYes = new Runnable() {

        @Override
        public void run() {
            mIconNight.setSelected(true);
            if (mService != null) {
                mService.setNightMode(UiModeManager.MODE_NIGHT_YES);
            }
        }
    };

    private final Runnable mDarkModeNightNo = new Runnable() {

        @Override
        public void run() {
            mIconNight.setSelected(false);
            if (mService != null) {
                mService.setNightMode(UiModeManager.MODE_NIGHT_NO);
            }
        }
    };

    private void updateDarkMode() {
        if (mService != null && mService.getNightMode() == UiModeManager.MODE_NIGHT_YES) {
            mIconNight.setSelected(true);
            mIconNight.setImageResource(R.drawable.iphone_control_panel_nightmode_on);
        } else {
            mIconNight.setSelected(false);
            mIconNight.setImageResource(R.drawable.iphone_control_panel_nightmode_off);
        }
    }

    private void updateScreenRecord() {
        if (mService != null && mService.getScreenRecord() != 0) {
            mIconRecorder.setImageResource(R.drawable.iphone_control_panel_screenrecord_on);
        } else {
            if (mRecorderCountDown > 3) {
                mIconRecorder.setImageResource(R.drawable.iphone_control_panel_screenrecord_off);
            }
        }
    }

    private void updateBrightness(int max, int min, int progress, boolean tracking) {
        if (!mAutomatic) {
            final int val = progress;
            if (!tracking) {
                if (mService != null) {
                    mService.setBrightnessValue(val);
                }
            }
        } else {
            final float adj = progress / (2048 / 2f) - 1; //BRIGHTNESS_ADJ_RESOLUTION = 2048
            if (!tracking) {
                if (mService != null) {
                    mService.setBrightnessAdj(adj);
                }
            }
        }
    }

    private int getCurrentBrightness() {
        float value = 108;
        if (mAutomatic) {
            if (mService != null) {
                value = mService.getBrightnessAdj();
            }
        } else {
            if (mService != null) {
                value = mService.getBrightnessCurrent();
            }
        }
        return (int) value;
    }

    private void updateVolumeState() {
        if (mService != null) {
            mVolumeProgress = mService.getStreamVolume(AudioManager.STREAM_MUSIC);
            mSlideControlVolume.setProgress(mVolumeProgress);
        }
    }

    private void updateBrightnessState() {
        int automatic = Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL;
        if (mService != null) {
            automatic = mService.getBrightnessAutomatic();
        }
        mAutomatic = automatic != Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL;
        mSlideControlBrightness.setProgress(getCurrentBrightness());
    }

    private void updateSilentMode() {
        if (mService != null) {
            int ringerMode = mService.getRingerMode();
            if ((ringerMode == AudioManager.RINGER_MODE_SILENT) || (ringerMode == AudioManager.RINGER_MODE_VIBRATE)) {
                mIconSilent.setSelected(true);
                mIconSilent.setImageResource(R.drawable.iphone_control_panel_silent_on);
            } else {
                mIconSilent.setSelected(false);
                mIconSilent.setImageResource(R.drawable.iphone_control_panel_silent_off);
            }
        }
    }

    @Override
    public void onClick(View v) {
        final int id = v.getId();
        if (id == R.id.ip_shortcut_icon_wifi) {
            if (mService != null && !mIsAirplaneMode) {
                if (mService.isWifiEnabled()) {
                    mIconWifi.setImageResource(R.drawable.iphone_control_panel_wifi_off);
                } else {
                    mIconWifi.setImageResource(R.drawable.iphone_control_panel_wifi_on);
                }
                mService.setWifiEnabled(!mWifiVisible);
            }
        } else if (id == R.id.ip_shortcut_icon_bt) {
            if (mService != null) {
                mService.setBluetoothEnabled(!mService.isBluetoothEnabled());
            }
        } else if (id == R.id.ip_shortcut_icon_airdrop) {
            if (mService != null && !mIsAirplaneMode) {
                if (mService.isHotspotEnabled()) {
                    mHotspotEnableInTouch = false;
                    mIconDrop.setImageResource(R.drawable.iphone_control_panel_mobile_off);
                    mService.setHotspotEnabled(false);
                } else {
                    mHotspotEnableInTouch = true;
                    mIconDrop.setImageResource(R.drawable.iphone_control_panel_mobile_on);
                    mService.setHotspotEnabled(true);
                }
            }
        } else if (id == R.id.ip_shortcut_icon_airplane) {
            if (mService != null) {
                mService.setAirplaneMode(!mIsAirplaneMode);
            }
        } else if (id == R.id.ip_shortcut_icon_lock) {
            if (mService != null) {
                mService.setRotationLocked(!mService.isRotationLocked());
            }
        } else if (id == R.id.ip_shortcut_icon_nodisturb) {
            boolean show = Settings.System.getInt(getContext().getContentResolver(), KEY_NO_DISTURB, 0) == 1;
            if (mService != null) {
                mService.setDisturbEnable(!show);
                updateNoDisturbState(!show);
            }
        } else if (id == R.id.ip_shortcut_icon_torch) {
            if (mService != null) {
                mService.setTorchEnabled(!mService.isTorchEnabled());
            }
        } else if (id == R.id.ip_shortcut_icon_clock) {
            startExternalApp("android.intent.action.DESK_CLOCK");
            if (mCallback != null) {
                mCallback.onAnimationCollapse();
            }
        } else if (id == R.id.ip_shortcut_icon_calc) {
            startExternalApp("com.android.sec.calculator", "com.android.sec.calculator.Calculator");
            if (mCallback != null) {
                mCallback.onAnimationCollapse();
            }
        } else if (id == R.id.ip_shortcut_icon_qrcode || id == R.id.ip_shortcut_icon_camera) {
            startExternalApp("android.media.action.STILL_IMAGE_CAMERA");
            if (mCallback != null) {
                mCallback.onAnimationCollapse();
            }
        } else if (id == R.id.ip_shortcut_icon_recorder) {
            if (mService != null && mService.getScreenRecord() != 0) {
                mService.setScreenRecording(false);
                mRecorderCountDown = 100;
            } else {
                if (mRecorderCountDown >= 0 && mRecorderCountDown <= 3) {
                    mRecorderCountDown = 100;
                } else {
                    mRecorderCountDown = 3;
                }
            }
            mHandler.removeCallbacks(mRecorderCountDownRunnable);
            mHandler.post(mRecorderCountDownRunnable);
        } else if (id == R.id.ip_shortcut_icon_night) {
            removeCallbacks(mDarkModeNightYes);
            removeCallbacks(mDarkModeNightNo);
            if (mIconNight.isSelected()) {
                mIconNight.setImageResource(R.drawable.iphone_control_panel_nightmode_off);
                postDelayed(mDarkModeNightNo, 500);
            } else {
                mIconNight.setImageResource(R.drawable.iphone_control_panel_nightmode_on);
                postDelayed(mDarkModeNightYes, 500);
            }
        } else if (id == R.id.ip_shortcut_icon_silent) {
            handleSilentButton();
            if (mVibrator != null) {
                mVibrator.vibrate(200);
            }
            Message msg = mHandler.obtainMessage(MSG_SILENT_UPDATE);
            mHandler.sendMessageDelayed(msg, 80);
        }
    }

    private void updateWifiAirplaneIcon() {
        updateWifiState();
        updateAirplaneState();
    }

    private void startExternalApp(String action) {
        try {
            Intent intent = new Intent(action);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            getContext().startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void startExternalApp(String pkg, String cls) {
        try {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.setClassName(pkg, cls);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            getContext().startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public ImageView getBluetoothButton() {
        return mIconBt;
    }

    public void onPanelExpandChanged(boolean expanded) {
        if (expanded) {
            updateVolumeState();
            updateBrightnessState();
            updateNoDisturbState();
            updateDarkMode();
            updateScreenRecord();
            updateSilentMode();
        }
    }

    private void updateWifiState() {
        if (mWifiVisible && !mIsAirplaneMode) {
            mIconWifi.setImageResource(R.drawable.iphone_control_panel_wifi_on);
            mBarWifi.setVisibility(VISIBLE);
            switch (mWifiLevel) {
                case 0:
                    mBarWifi.setImageResource(R.drawable.ip_ic_qs_wifi_0);
                    break;
                case 1:
                    mBarWifi.setImageResource(R.drawable.ip_ic_qs_wifi_1);
                    break;
                case 2:
                    mBarWifi.setImageResource(R.drawable.ip_ic_qs_wifi_2);
                    break;
                case 3:
                    mBarWifi.setImageResource(R.drawable.ip_ic_qs_wifi_3);
                    break;
                default:
                    mBarWifi.setImageResource(R.drawable.ip_ic_qs_wifi_4);
                    break;
            }
        } else {
            mIconWifi.setImageResource(R.drawable.iphone_control_panel_wifi_off);
            mBarWifi.setVisibility(GONE);
        }
    }

    private void updateAirplaneState() {
        if (mIsAirplaneMode) {
            mIconAirplane.setImageResource(R.drawable.iphone_control_panel_air_on);
            mBarSignalSim1.setImageResource(R.drawable.ip_ic_qs_airplane);
        } else {
            mIconAirplane.setImageResource(R.drawable.iphone_control_panel_air_off);
        }
    }

    private void updateBluetoothState(boolean enable) {
        if (enable) {
            mBarBluetooth.setVisibility(VISIBLE);
            mIconBt.setImageResource(R.drawable.iphone_control_panel_bt_on);
        } else {
            mBarBluetooth.setVisibility(GONE);
            mIconBt.setImageResource(R.drawable.iphone_control_panel_bt_off);
        }
    }

    private void updateHotspotState() {
        if (mService != null) {
            updateHotspotState(mService.isHotspotEnabled() && !mIsAirplaneMode);
        }
    }

    private void updateHotspotState(boolean enable) {
        if (enable) {
            mIconDrop.setImageResource(R.drawable.iphone_control_panel_mobile_on);
        } else {
            mIconDrop.setImageResource(R.drawable.iphone_control_panel_mobile_off);
        }
    }

    private void updateRotationLockState(boolean on) {
        if (on) {
            mIconScreenLock.setImageResource(R.drawable.iphone_control_panel_lock_on);
        } else {
            mIconScreenLock.setImageResource(R.drawable.iphone_control_panel_lock_off);
        }
    }

    private void updateFlashlightState(boolean enable) {
        if (enable) {
            mIconTorch.setImageResource(R.drawable.iphone_control_panel_flashlight_on);
        } else {
            mIconTorch.setImageResource(R.drawable.iphone_control_panel_flashlight_off);
        }
    }

    private void updateNoDisturbState() {
        boolean show = Settings.System.getInt(getContext().getContentResolver(), KEY_NO_DISTURB, 0) == 1;
        updateNoDisturbState(show);
    }

    private void updateNoDisturbState(boolean show) {
        if (show) {
            mIconNoDisturb.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.iphone_control_panel_focus_on),
                    null, null, null);
        } else {
            mIconNoDisturb.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.iphone_control_panel_focus_off),
                    null, null, null);
        }
    }

    private final int MSG_HOTSPOT_UPDATE = 3;
    private final int MSG_HEADSET = 4;
    private final int MSG_SILENT_UPDATE = 5;

    private void handleSilentButton() {
        if (mService != null) {
            int ringerMode = mService.getRingerMode();
            if (ringerMode == AudioManager.RINGER_MODE_NORMAL) {
                mService.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
            } else {
                mService.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
            }

            Intent actionintent = new Intent("android.ext.action_mute_key_switch");
            getContext().sendBroadcast(actionintent);
        }
    }

    private void handleActionButton() {
//        String currentActionButton = "silent";
//        currentActionButton = Settings.System.getString(mContext.getContentResolver(), "current_actionbutton");
//        if (currentActionButton == null) {
//            currentActionButton = "silent";
//        }
//        switch (currentActionButton) {
//            case "silent": {
//                handleSilentButton();
//            }
//            break;
//            case "focus": {
//                boolean show = Settings.System.getInt(mContext.getContentResolver(), KEY_NO_DISTURB, 0) == 1;
//                Settings.System.putInt(mContext.getContentResolver(), KEY_NO_DISTURB, show ? 0 : 1);
//            }
//            break;
//            case "camera": {
//                startExternalApp("android.media.action.STILL_IMAGE_CAMERA");
//            }
//            break;
//            case "flashlight": {
//                if (mFlashlightController != null && mFlashlightController.isAvailable()) {
//                    if (mFlashlightController.isEnabled()) {
//                        mFlashlightController.setFlashlight(false);
//                    } else {
//                        mFlashlightController.setFlashlight(true);
//                    }
//                }
//            }
//            break;
//            case "memos": {
//                startExternalApp("com.iphone.voiceremenberios7", "com.iphone.voiceremenberios7.MainActivity");
//            }
//            break;
//            case "magnifier": {
//                startExternalApp("android.media.action.STILL_IMAGE_CAMERA");
//            }
//            break;
//            case "shortcuts": {
//                int typeIndex = Settings.System.getInt(mContext.getContentResolver(), "shortcut_launch_index", -1);
//                if (typeIndex != -1) {
//                    String pkg = Settings.System.getString(mContext.getContentResolver(), "shortcut_launch_package_name");
//                    String cls = Settings.System.getString(mContext.getContentResolver(), "shortcut_launch_class_name");
//                    if (isApkExist(pkg)) {
//                        startExternalApp(pkg, cls);
//                    } else {
//                        Settings.System.putInt(mContext.getContentResolver(), "shortcut_launch_index", -1);
//                        startExternalApp("com.google.android.googlequicksearchbox", "com.google.android.googlequicksearchbox.SearchActivity");
//                    }
//                } else {
//                    startExternalApp("com.google.android.googlequicksearchbox", "com.google.android.googlequicksearchbox.SearchActivity");
//                }
//            }
//            break;
//            case "accessibility": {
//                startExternalApp("com.google.android.apps.googleassistant", "com.google.android.apps.googleassistant.AssistantActivity");
//            }
//            break;
//            default:
//                break;
//        }
//
//        if (mVibrator != null) {
//            mVibrator.vibrate(200);
//        }
    }

    private boolean isApkExist(String pkg) {
        try {
            getContext().getPackageManager().getApplicationInfo(pkg, PackageManager.MATCH_ALL);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    private final Handler mHandler = new Handler(Looper.myLooper()) {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_HOTSPOT_UPDATE:
                    updateHotspotState(msg.arg1 == 1);
                    break;
                case MSG_HEADSET:
                    if (mEarphonePlugState == 0) {
                        mBarHeadset.setVisibility(GONE);
                    } else if (mEarphonePlugState == 1) {
                        mBarHeadset.setVisibility(VISIBLE);
                        mBarHeadset.setImageResource(R.drawable.ic_headset);
                    } else if (mEarphonePlugState == 2) {
                        mBarHeadset.setVisibility(VISIBLE);
                        mBarHeadset.setImageResource(R.drawable.ic_headset_mic);
                    }
                    break;
                case MSG_SILENT_UPDATE:
                    updateSilentMode();
                    break;
            }
        }
    };

    @Override
    public void onDisturbChanged(boolean open) {
        updateNoDisturbState(open);
    }

    @Override
    public void onBrightnessChanged(boolean auto, int brightness) {
        updateBrightnessState();
    }

    @Override
    public void onAirplaneModeChanged(boolean open) {
        mIsAirplaneMode = open;
        updateWifiAirplaneIcon();
        updateHotspotState();
    }

    @Override
    public void onHotspotStateChanged(boolean enabled, int numDevices) {
        if (mHotspotEnableInTouch) {
            if (!enabled) {
                Message msg = mHandler.obtainMessage(MSG_HOTSPOT_UPDATE);
                msg.arg1 = 0;
                mHandler.sendMessageDelayed(msg, 2000);
            } else {
                mHotspotEnableInTouch = false;
                mHandler.removeMessages(MSG_HOTSPOT_UPDATE);
                updateHotspotState(true);
            }
        } else {
            updateHotspotState(enabled);
        }
    }

    @Override
    public void onGpsChanged(boolean open, boolean active) {

    }

    @Override
    public void onBluetoothChanged(boolean open, boolean connected, String name) {
        updateBluetoothState(open);
    }

    @Override
    public void onWifiChanged(boolean open, boolean connected, int signal, int network, String name) {
        mWifiVisible = open;
        mWifiLevel = signal;
        updateWifiAirplaneIcon();
    }

    @Override
    public void onSimStateChanged(int count, int subId, boolean insert, int signal, int network, int dataType, String name) {
        if (count == 0) {
            mBarSignalSim1.setImageResource(0);
            mBarSignalSim2.setImageResource(0);
            mBarCarrierSim1.setText("");
            mBarCarrierSim2.setText("");
            mBarTypeSim1.setImageResource(0);
            mBarTypeSim2.setImageResource(0);
        } else if (count == 1) {
            if (signal == 11) { // 11:airplane  12:searching
                mBarSignalSim1.setImageResource(R.drawable.ip_ic_qs_airplane);
                mBarCarrierSim1.setText("");
                mBarTypeSim1.setImageResource(0);
            } else {
                mBarSignalSim1.setImageResource(Constants.SingleSimStrengthIds[Math.max(Math.min(signal, 4), 0)]);
                mBarTypeSim1.setImageResource(Constants.getNetworkIconId(network));
                mBarCarrierSim1.setText(name);
            }
        } else {
            if (subId == 1) {
                mBarSignalSim1.setImageResource(Constants.SingleSimStrengthIds[Math.max(Math.min(signal, 4), 0)]);
                mBarTypeSim1.setImageResource(Constants.getNetworkIconId(network));
                mBarCarrierSim1.setText(name);
            } else if (subId == 2) {
                mBarSignalSim2.setImageResource(Constants.SingleSimStrengthIds[Math.max(Math.min(signal, 4), 0)]);
                mBarTypeSim2.setImageResource(Constants.getNetworkIconId(network));
                mBarCarrierSim2.setText(name);
            }
        }
        if (!mWifiVisible) {
            if (dataType != 0) {
                mBarWifi.setVisibility(VISIBLE);
                mBarWifi.setImageResource(Constants.getNetworkIconId(network));
            } else {
                mBarWifi.setVisibility(GONE);
            }
        }

        if (count > 1) {
            mBarLine2Layout.setVisibility(VISIBLE);
        } else {
            mBarLine2Layout.setVisibility(GONE);
        }
    }

    @Override
    public void onTorchChanged(boolean available, boolean open) {
        updateFlashlightState(open);
    }

    @Override
    public void onAudioStateChanged(int stream, int volume, boolean silent, boolean vibrate) {

    }

    @Override
    public void onScreenAutoRotationChanged(boolean open) {
        updateRotationLockState(open);
    }

    @Override
    public void onScreenRecordingChanged(int state, int time) {

    }

    @Override
    public void onBatteryChanged(int level, boolean pluggedIn, boolean charging, boolean powerSave) {

    }
}
